/* eslint-disable func-names */
/* eslint-disable react/no-unused-state */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/camelcase */
/* eslint-disable max-len */
/* eslint-disable consistent-return */
/**
 * Created by zhangsong on 2019-05-08.
 */
import Power from '@/constants/power';
import Authorized from '@/utils/Authorized';
import InputGroupGrid from '@/components/InputGroupGrid';
import React, { Component } from 'react';
import moment from 'moment';
import {
  Form,
  Input,
  DatePicker,
  Button,
  Radio,
  Upload,
  Icon,
  Spin,
  Modal,
  Row,
  Col,
  Tooltip,
  Select,
  Checkbox,
  message,
  Switch,
  Table
} from 'antd';
import { connect } from 'dva';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { formatMessage, FormattedMessage, getLocale } from '@/utils/i18n';
import VaccineReducer from '@/dva/application/vaccine';
// import UserReducer from '@/dva/user';
import { ContractorApplication } from '@/constants/routes';
import { WorkCardDefault } from '@/constants/styleConfig';
import PDFPreview from '@/components/PDFPreview';
import { getBase64, getPageQuery } from '@/utils/utils';
import _ from 'lodash';
import CryptoJS from 'crypto-js';
import { downloadPartb } from '@/services/application/vaccine';
import AlarmReducer from '@/dva/application/alarmemail';

import Style from '../index.module.scss';

const { Namespace, Effects, Reducers } = VaccineReducer;

@connect(
  state => ({
    contractorStore: state[Namespace],
  }),
  dispatch => ({
    uploadFile: data =>
      dispatch({
        type: `${Namespace}/${Effects.uploadfile}`,
        data,
      }),
    setData: () =>
      dispatch({
        type: `${Namespace}/${Effects.setData}`,
      }),
    downLoadXlsx: data =>
      dispatch({
        type: `${Namespace}/${Effects.downLoadXlsx}`,
        data,
      }),
  }),
)
@Form.create()
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      previewVisible: false,
      previewImage: '',
      loading: false,
    };
  }

  normFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  onUpload = file => {
    const { uploadFile, setData } = this.props;
    setData();
    const formData = new FormData();
    formData.append('file', file)
    uploadFile(formData)
  }

  // 显示头像预览
  handlePhotographPreview = async file => {
    if (file.type === 'application/pdf') {
      Modal.info({ title: formatMessage('applicationContractor.tips.noSupportedPDF') });
      return;
    }
    if (!file.url) {
      if (file.response) {
        file.thumbUrl = file.response;
      } else {
        file.thumbUrl = await getBase64(file.originFileObj);
      }
    }

    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  componentDidMount() {
    this.props.setData();
  }


  handleSubmit = e => {
    e.preventDefault();
    const { form, handleSubmit, userStore, contractorStore } = this.props;
    // let contractNumber = null;

    form.validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        console.log('看看这个文件的东西', values)
      }
    });
  }

  onDownload = async () => {
    const res = this.props.downLoadXlsx();
    console.log('点击下载的时候', res);
  }

  renderColumns = () => [
    {
      title: formatMessage({ id: 'baseInfo.serialnumber' }),
      dataIndex: 'passNo',
      render: (text, record, index) => {
        return (
          <div>
            {index + 1}
          </div>
        );
      },
    },
    {
      title: formatMessage('applicationCommon.readerCard.passno'),
      dataIndex: 'passNo',
    },
    {
      title: formatMessage({ id: 'baseInfo.enddate' }),
      dataIndex: 'projectExpire',
    },
    {
      title: formatMessage({ id: 'baseInfo.reasonfail' }),
      dataIndex: 'result',
    },
  ]

  render() {
    const { form, contractorStore = {}, userStore = {}, alarmemailStore = {} } = this.props;
    const { isModalVisible } = this.state;
    const { getFieldDecorator } = form;
    const { saveLoading, vaccinedetial, partbinfo } = contractorStore;
    const {
      xslloading,
    } = alarmemailStore;
    return (
      <PageHeaderWrapper>
        <Spin spinning={!!saveLoading} size="large">
          <div className={`${Style.body} contractor-add-wrapper`}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '20px' }}>
              <div style={{ marginRight: '5px' }}>{formatMessage('applicationCommon.workerCard.partbtimedown')}</div>
              <Button type="primary" icon="download" size="small" loading={xslloading} onClick={() => this.onDownload()}>
                Download
              </Button>
            </div>
            <duv className={Style.row}>
              {formatMessage('applicationCommon.workerCard.partbtimetitle')}
            </duv>

            <div>
              <Form labelAlign="right" onSubmit={this.handleSubmit}>
                <Form.Item
                  style={{ padding: 0 }}
                  label={formatMessage('applicationContractor.columns.annexes.name')}
                // extra="表格扫描文件"
                >
                  {getFieldDecorator('id_base64', {
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                  })(
                    <Upload
                      name="logo"
                      accept=".xlsx"
                      customRequest={async ({ file, onSuccess }) => {
                        this.onUpload(file);
                        const base64 = await new Promise(resolve => {
                          const fileReader = new FileReader();
                          fileReader.readAsDataURL(file);
                          // fileReader.onload = () => {
                          //   resolve(fileReader.result);
                          // };
                        });
                        onSuccess(base64);
                        return {
                          abort() { },
                        };
                      }}
                      showUploadList={false}
                      listType="picture"
                      onPreview={this.handlePhotographPreview}
                    >
                      <Button>
                        <Icon type="upload" />
                        {formatMessage('applicationStaff.columns.annexes.button')}
                      </Button>
                    </Upload>,
                  )}
                </Form.Item>
              </Form>
            </div>
            {
              partbinfo?.failList?.length > 0 ? (
                <>
                  <div style={{ display: 'flex', alignItems: 'center', marginTop: '10px' }}>
                    <div style={{ marginRight: '15px' }}> {formatMessage('baseInfo.totalnum')}{partbinfo?.sum}</div>
                    <div style={{ marginRight: '15px' }}> {formatMessage('baseInfo.succnum')}{partbinfo?.successNum}</div>
                    <div style={{ marginRight: '15px' }}> {formatMessage('baseInfo.errornum')}{partbinfo?.failNum}</div>
                  </div>
                  <div className={Style.main}>
                    <div className={Style.detailWrapper} >
                      <Table
                        scroll={{ x: 'max-content', y: 350 }}
                        loading={!!saveLoading}
                        rowKey="id"
                        columns={this.renderColumns()}
                        pagination={false}
                        dataSource={partbinfo?.failList}
                      />
                    </div>
                  </div>
                </>
              ) : null

            }

          </div>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default Index;
